// 引入
import Vue from 'vue'
import VueRouter from 'vue-router'

// 引入子组件
import Login from '../components/login/Login.vue'

// 拆离出去7个
const Home = () => import('../components/home/Home.vue')
const Users = () => import('../components/users/Users.vue')
const Roles = () => import('../components/roles/Roles.vue')
const Rights = () => import('../components/rights/Rights.vue')
const Categories = () => import('../components/categories/Categories.vue')
const Goods = () => import('../components/goods/Goods.vue')
const GoodsAdd = () => import('../components/goods/GoodsAdd.vue')

// 在模块化工程中 Vue.use()
Vue.use(VueRouter)

// 实例化router
const router = new VueRouter({
  routes: [
    // 重定向
    { path: '/', redirect: '/login' },
    { path: '/login', name: 'login', component: Login },
    {
      path: '/home',
      name: 'home',
      component: Home,
      children: [
        { path: '/users/:page?', name: 'users', component: Users },
        { path: '/roles', name: 'roles', component: Roles },
        { path: '/rights', name: 'rights', component: Rights },
        { path: '/categories', name: 'categories', component: Categories },
        { path: '/goods', name: 'goods', component: Goods },
        { path: '/goods-add', name: 'goods-add', component: GoodsAdd }
      ]
    }
  ]
})

// 全局前置导航守卫  是 router 里面的一个方法
// to : 目标路由对象
// from : 来源路由对象
// next 下一步
//     next() 允许下一步/允许访问
//     next(false) 不允许
//     next('/login') 跳login
router.beforeEach((to, from, next) => {
  // 1. 判断是否是登录页
  // 登录页面
  if (to.path === '/login') {
    next()
    // 非登录页面 (其他页面)
  } else {
    // 2. 判断是否登录过
    const token = localStorage.getItem('token')
    token ? next() : next('/login')
  }
})

// 导出
export default router
